/**
 * 模拟工具执行器 - 仅用于测试
 */

import { ToolExecutor } from '../../message-broker';

export class MockToolExecutor implements ToolExecutor {
  private executionDelay: number;
  private shouldFail: boolean;
  private failureRate: number;
  private executionHistory: Array<{
    toolName: string;
    input: any;
    timestamp: Date;
    success: boolean;
  }> = [];

  constructor(options: {
    executionDelay?: number;
    shouldFail?: boolean;
    failureRate?: number;
  } = {}) {
    this.executionDelay = options.executionDelay ?? 500;
    this.shouldFail = options.shouldFail ?? false;
    this.failureRate = options.failureRate ?? 0;
  }

  async executeToolUse(toolName: string, input: any, options: any): Promise<any> {
    const startTime = Date.now();
    
    // 记录执行历史
    const historyEntry = {
      toolName,
      input,
      timestamp: new Date(),
      success: false
    };

    try {
      // 模拟执行延迟
      await this.delay(this.executionDelay);

      // 检查是否应该失败
      const shouldFailThisTime = this.shouldFail || 
        (this.failureRate > 0 && Math.random() < this.failureRate);

      if (shouldFailThisTime) {
        throw new Error(`Mock tool execution failed for ${toolName}`);
      }

      // 根据工具名称生成不同的模拟结果
      const result = this.generateMockResult(toolName, input);
      
      historyEntry.success = true;
      this.executionHistory.push(historyEntry);

      return {
        success: true,
        output: result,
        metadata: {
          executionTime: Date.now() - startTime,
          timestamp: new Date(),
          mock: true,
          toolName
        }
      };

    } catch (error) {
      this.executionHistory.push(historyEntry);
      
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
        metadata: {
          executionTime: Date.now() - startTime,
          timestamp: new Date(),
          mock: true,
          toolName
        }
      };
    }
  }

  private generateMockResult(toolName: string, input: any): any {
    switch (toolName) {
      case 'view':
        return {
          content: `// Mock content for ${input.path || 'unknown file'}\nconsole.log('Mock file content');`,
          lines: 2,
          mock: true
        };

      case 'edit':
        return {
          success: true,
          changes: `Mock edit applied to ${input.path || 'unknown file'}`,
          mock: true
        };

      case 'search':
        return {
          results: [
            { file: 'mock-file1.ts', line: 10, content: 'Mock search result 1' },
            { file: 'mock-file2.ts', line: 25, content: 'Mock search result 2' }
          ],
          total: 2,
          mock: true
        };

      case 'run':
        return {
          stdout: 'Mock command output',
          stderr: '',
          exitCode: 0,
          mock: true
        };

      default:
        return {
          message: `Mock execution of ${toolName} completed successfully`,
          input,
          mock: true
        };
    }
  }

  // 测试辅助方法
  setShouldFail(shouldFail: boolean): void {
    this.shouldFail = shouldFail;
  }

  setExecutionDelay(delay: number): void {
    this.executionDelay = delay;
  }

  setFailureRate(rate: number): void {
    this.failureRate = Math.max(0, Math.min(1, rate));
  }

  getExecutionHistory(): typeof this.executionHistory {
    return [...this.executionHistory];
  }

  clearExecutionHistory(): void {
    this.executionHistory = [];
  }

  getSuccessRate(): number {
    if (this.executionHistory.length === 0) return 1;
    const successCount = this.executionHistory.filter(h => h.success).length;
    return successCount / this.executionHistory.length;
  }

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}
